package org.dromara.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.finance.domain.Staff;
import org.dromara.finance.domain.vo.CustomerCategoryVo;
import org.dromara.finance.mapper.CustomerCategoryMapper;
import org.dromara.finance.utils.ContractReferenceCheckUtil;
import org.springframework.stereotype.Service;
import org.dromara.finance.domain.bo.CustomerBo;
import org.dromara.finance.domain.vo.CustomerVo;
import org.dromara.finance.domain.Customer;
import org.dromara.finance.mapper.CustomerMapper;
import org.dromara.finance.service.ICustomerService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 客户信息Service业务层处理
 *
 * @author xxy
 * @date 2025-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class CustomerServiceImpl implements ICustomerService {

    private final CustomerMapper baseMapper;
    private final CustomerCategoryMapper customerCategoryMapper;

    private final ContractReferenceCheckUtil contractReferenceCheckUtil;

    /**
     * 查询客户信息
     *
     * @param id 主键
     * @return 客户信息
     */
    @Override
    public CustomerVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询客户信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 客户信息分页列表
     */
    @Override
    public TableDataInfo<CustomerVo> queryPageList(CustomerBo bo, PageQuery pageQuery) {
        QueryWrapper<Customer> qw = buildQueryWrapper(bo);
        Page<CustomerVo> result = baseMapper.selectPageList(pageQuery.build(), qw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的客户信息列表
     *
     * @param bo 查询条件
     * @return 客户信息列表
     */
    @Override
    public List<CustomerVo> queryList(CustomerBo bo) {
        QueryWrapper<Customer> qw = buildQueryWrapper(bo);
        return baseMapper.selectExportList(qw);
    }

    private QueryWrapper<Customer> buildQueryWrapper(CustomerBo bo) {
        QueryWrapper<Customer> qw = new QueryWrapper<>();
        qw.eq(bo.getId() != null, "c.id", bo.getId());
        qw.eq(StringUtils.isNotBlank(bo.getCode()), "c.code", bo.getCode());
        qw.like(StringUtils.isNotBlank(bo.getName()), "c.name", bo.getName());
        qw.eq(bo.getCategoryId() != null, "c.category_id", bo.getCategoryId());
        qw.eq(bo.getCustomerStatus() != null, "c.customer_status", bo.getCustomerStatus());
        qw.orderByAsc("c.id");
        return qw;
    }


    /**
     * 新增客户信息
     *
     * @param bo 客户信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(CustomerBo bo) {
        Customer add = MapstructUtils.convert(bo, Customer.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改客户信息
     *
     * @param bo 客户信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(CustomerBo bo) {
        Customer update = MapstructUtils.convert(bo, Customer.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Customer entity){
        //TODO 做一些数据校验,如唯一约束
        QueryWrapper<Customer> wrapper = new QueryWrapper<>();
        wrapper.eq("code", entity.getCode());

        // 如果是修改，排除自身
        if (entity.getId() != null) {
            wrapper.ne("id", entity.getId());
        }

        Long count = baseMapper.selectCount(wrapper);
        if (count != null && count > 0) {
            throw new RuntimeException("客户编码已存在");
        }
        //name去重
        QueryWrapper<Customer> nameWrapper = new QueryWrapper<>();
        nameWrapper.eq("name", entity.getName());
        if (entity.getId() != null) {
            nameWrapper.ne("id", entity.getId());
        }
        Long nameCount = baseMapper.selectCount(nameWrapper);
        if (nameCount != null && nameCount > 0) {
            throw new RuntimeException("客户名称已存在");
        }

        if (entity.getCustomerStatus() == 1) {
            CustomerCategoryVo categoryVo = customerCategoryMapper.selectVoById(entity.getCategoryId());
            if (categoryVo.getCustomerCategoryStatus() == 2) {
                throw new RuntimeException("该客户所在分类客已停用，禁止启用!");
            }
        }
    }

    /**
     * 校验并批量删除客户信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            contractReferenceCheckUtil.checkReferenceArchive("sale_contract", "customer_id", ids, "客户");
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
